
$(function () {
    showQR();

    var spread = new GcSpread.Sheets.Spread($("#ss")[0], { newTabVisible: false });
    var sheet = spread.sheets[0];
    spread.isPaintSuspended(true);
    initSpread(spread);
    resetDefaultStyle(sheet);

    BindingSalesData(sheet);
    setRowStripStyle(sheet);
    setTotolCalc(sheet);
    setStyle(sheet);
    setConditionalFormats(sheet);
    setRangeGroup(sheet);
    setRowFilter(sheet);

    // sheet.setIsProtected(true);
    sheet.protectionOption().allowResizeColumns = true;
    sheet.protectionOption().allowFilter = true;
    sheet.protectionOption().allowSort = true;

    spread.isPaintSuspended(false);

    $(".tipModal").click(function(){
        $("#helpButton").show();
        var dialog = $(".tipModal");
        dialog.animate({height:0,width:0,top:"100%"}, 500, "",function(){
        });
        $('.modal-backdrop').hide();
    })

    $("#helpButton").click(function(){
        var dialog = $(".tipModal");
        // dialog.animate({height:document.body.offsetHeight,width:document.body.offsetWidth}, 500)
        dialog.animate({height: "100%",width: "100%",top:0}, 500)
        $('.modal-backdrop').show();
        $("#helpButton").hide();
    $("body").scrollTop(0);
    })
    
    window.onorientationchange = orientationChange;
});

function showQR(){
     var sUserAgent = navigator.userAgent.toLowerCase();
    //  alert(sUserAgent)
      var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";   
       var bIsIphoneOs = sUserAgent.match(/iphone/i) == "iphone"; 
       var bIsAndroid = sUserAgent.match(/android/i) == "android"; 
     if(bIsIpad || bIsIphoneOs || bIsAndroid){
         $("#qr").hide();
     }
     else{
         $("#qr").show();
     }

     $("#qrClose").click(function(){
         $("#qr").hide();
     })
}

function orientationChange(e) {
    // if(document.body.offsetHeight > document.body.offsetWidth){
        var spread = $("#ss").data("spread");
        spread.getActiveSheet().endEdit(true);
        spread.refresh();
      //  alert("0")
    //}
    
    //alert(document.body.offsetHeight + " " + document.body.clientHeight + " " + document.body.scrollHeight)

    // $("#ss").css("height", document.body.offsetHeight);
    // var spread = $('#ss').data('spread');
    // spread.refresh()
    // alert($("body").css("height"))
    // setTimeout(function(){
    //     $("body").scrollTop(0);
    // },500)
}
function initSpread(spread) {
    // give sheet name more space
    spread.setTabStripRatio(0.8);
    spread.scrollbarMaxAlign(true);
    spread.scrollbarShowMax(true);
    spread.showVerticalScrollbar(false);
    GcSpread.Sheets.Culture("zh-cn");
}

function resetDefaultStyle(sheet) {
    // set default style for all cells
    sheet.defaults.rowHeight = 30;
	sheet.defaults.colHeaderRowHeight = 30;
    sheet.defaults.colWidth = 70;
    var defaultStyle = sheet.getDefaultStyle();
    defaultStyle.font = '16px 微软雅黑';
    defaultStyle.vAlign = GcSpread.Sheets.VerticalAlign.center;
    defaultStyle.locked = false;
    sheet.setDefaultStyle(defaultStyle);
}

function setRangeGroup(sheet) {
    sheet.colRangeGroup.direction = GcSpread.Sheets.RangeGroupDirection.Backward;
    sheet.colRangeGroup.group(4, 2);
    sheet.colRangeGroup.group(7, 2);
    sheet.colRangeGroup.group(10, 2);
    sheet.colRangeGroup.group(13, 2);
}

// set Produt Model
function ProductSales(productID, productName, unitPrice, year) {
    this.productID = productID;
    this.productName = productName;
    this.unitPrice = unitPrice;
    this.year = year;
}

function getProductSalesData() {
    var productNames = ["iPhone 6s Plus", "Lumia 930", "HuaWei 5", "XiaoMi 4"]
    var productSalesData = [];
    productNames.forEach(function (value, index) {
        var productSales = new ProductSales(index + 1, value, Math.round(Math.random() * 10000) / 100, 2015);
        for (var mon = 1; mon <= 12; mon++) {
            productSales["quantity" + mon] = Math.round(Math.random() * 1000);
        }
        productSalesData.push(productSales);
    });

    return productSalesData;
}

function BindingSalesData(sheet) {
    sheet.setName("2015销售数据");

    var datasource = getProductSalesData();

    var colInfos = [
        { name: 'productID', displayName: '产品编号', size: 100 },
        { name: 'productName', displayName: '产品名称', size: 170 },
        { name: 'unitPrice', displayName: '单价', formatter: '¥#,##0.00', size: 70 },
        { name: 'quantity1', displayName: '一月', size: 60, resizable: false },
        { name: 'quantity2', displayName: '二月', size: 60, resizable: false },
        { name: 'quantity3', displayName: '三月', size: 60, resizable: false },
        { name: 'quantity4', displayName: '四月', size: 60, resizable: false },
        { name: 'quantity5', displayName: '五月', size: 60, resizable: false },
        { name: 'quantity6', displayName: '六月', size: 60, resizable: false },
        { name: 'quantity7', displayName: '七月', size: 60, resizable: false },
        { name: 'quantity8', displayName: '八月', size: 60, resizable: false },
        { name: 'quantity9', displayName: '九月', size: 60, resizable: false },
        { name: 'quantity10', displayName: '十月', size: 60, resizable: false },
        { name: 'quantity11', displayName: '十一月', size: 60, resizable: false },
        { name: 'quantity12', displayName: '十二月', size: 60, resizable: false },
    ];
    sheet.autoGenerateColumns = false;
    sheet.setDataSource(datasource);
    sheet.bindColumns(colInfos);

}

function setRowStripStyle(sheet){
    var rowCount = sheet.getRowCount();
    var firstRowStyle = new GcSpread.Sheets.Style();
    var secondRowStyle = new GcSpread.Sheets.Style();

    firstRowStyle.backColor = "#edd9c0";
    firstRowStyle.borderLeft = new GcSpread.Sheets.LineBorder("#a8b6bf", GcSpread.Sheets.LineStyle.thin);
    secondRowStyle.backColor = "#c9d8c5";
    secondRowStyle.borderLeft = new GcSpread.Sheets.LineBorder("#a8b6bf", GcSpread.Sheets.LineStyle.thin);

    for(var i = 0; i< rowCount; i++){
        if(i % 2 === 0){
            sheet.setStyle(i, -1, firstRowStyle, GcSpread.Sheets.SheetArea.viewport);
        }
        else{
            sheet.setStyle(i, -1, secondRowStyle, GcSpread.Sheets.SheetArea.viewport);
        }
    } 
}

function setTotolCalc(sheet) {
    var rowCount, colCount;
    rowCount = sheet.getRowCount();
    colCount = sheet.getColumnCount();

    // add 2 column after last column
    sheet.addColumns(colCount, 2);
    sheet.setValue(0, colCount, "销量合计", GcSpread.Sheets.SheetArea.colHeader);
    sheet.setValue(0, colCount + 1, "金额合计", GcSpread.Sheets.SheetArea.colHeader);
    sheet.setColumnWidth(colCount, 100, GcSpread.Sheets.SheetArea.viewport);
    sheet.setColumnWidth(colCount + 1, 120, GcSpread.Sheets.SheetArea.viewport);

    for (var i = 0; i < rowCount; i++) {
        //set sum formula
        sheet.setFormula(i, colCount, "SUM(D" + (i + 1) + ":O" + (i + 1) + ")");
        sheet.setFormula(i, colCount + 1, "SUM(D" + (i + 1) + ":O" + (i + 1) + ") * C" + (i + 1));

        // set format for totol column
        sheet.setFormatter(i, colCount, "0", GcSpread.Sheets.SheetArea.viewport);
        sheet.setFormatter(i, colCount + 1, "¥#,##0.00", GcSpread.Sheets.SheetArea.viewport);
    }

    //add a new row for total
    sheet.addRows(rowCount, 1);
    sheet.addSpan(rowCount, 0, 1, 3);
    sheet.setValue(rowCount, 0, "数据统计");
    for (var j = 0; j < 14; j++) {
        var colS = String.fromCharCode("D".charCodeAt(0) + j)
        sheet.setFormula(rowCount, j + 3, "SUM(" + colS + "1:" + colS + rowCount + ")");
    }
    sheet.setFormatter(rowCount, colCount + 1, "¥#,##0.00", GcSpread.Sheets.SheetArea.viewport);
}

function setStyle(sheet) {
    var defaultStyle = sheet.getDefaultStyle();

    //use a html element to get font string
    var fontElement = $("<span></span>");
    fontElement.css("font", defaultStyle.font);
    fontElement.css("font-weight", 'bold');
    fontElement.css("font-size", '14px');
    var totalStyle = new GcSpread.Sheets.Style();
    totalStyle.font = fontElement.css("font");
    totalStyle.locked = true;
    totalStyle.backColor = "#7d4627";
    totalStyle.foreColor = "#13dbad";
    totalStyle.borderLeft = new GcSpread.Sheets.LineBorder("#a8b6bf", GcSpread.Sheets.LineStyle.thin);

    //set Totol data style, bold and locked
    var rowCount, colCount;
    rowCount = sheet.getRowCount();
    colCount = sheet.getColumnCount();
    sheet.setStyle(rowCount - 1, -1, totalStyle, GcSpread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, colCount - 1, totalStyle, GcSpread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, colCount - 2, totalStyle, GcSpread.Sheets.SheetArea.viewport);

    sheet.getCells(0, colCount - 2, rowCount - 2, colCount - 1).backColor("#7d4627")


    //productID style, set id horizontal align center
    var productIDStyle = new GcSpread.Sheets.Style();
    productIDStyle.hAlign = GcSpread.Sheets.HorizontalAlign.center;
    sheet.setStyle(-1, 0, productIDStyle, GcSpread.Sheets.SheetArea.viewport);
}

function setConditionalFormats(sheet) {
    var rowCount = sheet.getRowCount();
    var lessStyle = new GcSpread.Sheets.Style();
    lessStyle.foreColor = "red";
    var greaterStyle = new GcSpread.Sheets.Style();
    greaterStyle.foreColor = "green";
    //if value less than 100, then set color red
    sheet.getConditionalFormats().addCellValueRule(GcSpread.Sheets.ComparisonOperator.LessThan, 100, null, lessStyle, [new GcSpread.Sheets.Range(0, 3, rowCount - 1, 12)]);
    //if value greater than 900, then set color green
    sheet.getConditionalFormats().addCellValueRule(GcSpread.Sheets.ComparisonOperator.GreaterThan, 900, null, greaterStyle, [new GcSpread.Sheets.Range(0, 3, rowCount - 1, 12)]);
}

function setRowFilter(sheet) {
    var rowCount, colCount;
    rowCount = sheet.getRowCount();
    colCount = sheet.getColumnCount();
    var cellrange = new GcSpread.Sheets.Range(0, 0, rowCount - 1, colCount);
    var hideRowFilter = new GcSpread.Sheets.HideRowFilter(cellrange);
    sheet.rowFilter(hideRowFilter);
}